﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Xml;

namespace FIleForensics
{
    /// <summary>
    /// Summary description for Uploader
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Uploader : System.Web.Services.WebService
    {

        [WebMethod]
        public string UploadFile(byte[] f, string fileName)
        {

            string path = System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/") + fileName;

            try
            {

                using (MemoryStream ms = new MemoryStream(f))
                {
                    using (FileStream fs = new FileStream(path, FileMode.Create))
                    {

                        ms.WriteTo(fs);
                        return "OK";
                    }
                }
            }

            catch (Exception ex)
            {
                return ex.Message.ToString();
            }

        }

        [WebMethod]
        public string SetMeta(string xmlFileName, Metadata xmlData)
        {
            string xmlPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/") + xmlFileName;        

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = "  ";
            settings.NewLineOnAttributes = true;
            try
            {
                using (XmlWriter writer = XmlWriter.Create(xmlPath, settings))
                {
                    writer.WriteComment("File and crime scene information");
                    writer.WriteStartElement("Metadata");
                    writer.WriteStartElement("File");
                    writer.WriteAttributeString("filename", xmlData.filename);
                    writer.WriteElementString("CrimeSceneID", xmlData.crimeSceneID);
                    writer.WriteElementString("InvestigatorID", xmlData.investigatorID);
                    writer.WriteElementString("SHA1Sum", xmlData.sha1);
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.Flush();
                }

                return "Meta Data Created";
            }
            catch (Exception e)
            {
                return "Error writting meta data" + e;
            }
        }


    }
}
